/* Author: Stephan Pfaff (http://stephanpfaff.com)

*/





/* =========================================================================================================================
 * #############################################        Button        ######################################################
 * =========================================================================================================================
 */

/**
 * The Button Object
 * @param vars object providing the button properties (loaded from the database)
 * @return
 */
function Button(vars){
	if(vars != null) {
		try {
			Item.call(this, vars.prefix, vars.id, vars.type, vars.basename, vars.path, vars.label, vars.alias, vars.thumb, vars.thumb_enable, false, vars.item_class);
			this.category_id 	= parseInt(vars.category_id);
			this.project_id 	= parseInt(vars.project_id);
			if (vars.img != null && vars.img != '')
				this.img 		= siteRoot+vars.img;
			this.img_title		= vars.img_title;
			this.img_enable 	= vars.img_enable;
			this.lightbox_enable = vars.lightbox_enable;
			this.x				= parseInt(vars.x);
			this.y				= parseInt(vars.y);
			this.content_x		= parseInt(vars.content_x);
			this.content_y		= parseInt(vars.content_y);
			this.content_width	= parseInt(vars.content_width);
			this.content_height	= parseInt(vars.content_height);
			this.interactive	= vars.interactive;
			this.text			= vars.text;
			this.text_enable	= vars.text_enable;
			this.link			= vars.link;
			this.link_enable	= vars.link_enable;
			this.img_delete 	= false;
		} catch (e) {
			if(debug) alert('Initialization of Button failed, missing or wrong parameter! ('+e+')');
		}
	} else {
		try {
			var basename = '';
			var path = '';
			var project_id = 0;
			if(getProjects().currentItem() != null) {
				basename 		= getCategories().currentItem().alias + '_'
								+ getProjects().currentItem().alias + '_'
								+ $('#btn_alias').val();
				path 			= getCategories().currentItem().alias + '/'
								+ getProjects().currentItem().alias + '/';
								//+ $('#btn_alias').val() + '/';
				project_id = getProjects().currentItem().id;
			} else if(getCategories().currentItem() != null) {
				basename 		= getCategories().currentItem().alias + '_'
								+ $('#btn_alias').val();
				path 			= getCategories().currentItem().alias + '/intro/';
								//+ $('#btn_alias').val() + '/';
				project_id = 0;
			} else {
				alert('Wähle erst ein Element aus!');
			}
			Item.call(this,
					'btn',
					0,
					"button",
					basename,
					path,
					'',
					$('#btn_alias').val(),
					'',
					false,
					false,
					'');
			this.category_id 	= getCategories().currentItem().id;
			this.project_id 	= project_id;
			this.img 			= '';
			this.img_title		= '';
			this.img_enable 	= false;
			this.lightbox_enable = false;
			this.x				= 0;
			this.y				= 0;
			this.content_x		= 0;
			this.content_y		= 0;
			this.content_width	= 1;
			this.content_height	= 1;
			this.interactive	= 1;
			this.text			= '';
			this.text_enable	= false;
			this.link			= '';
			this.link_enable	= false;
			this.img_delete 	= false;
		} catch (e) {
			if(debug) alert('Initialization of new empty Button failed, missing or wrong parameter! ('+e+')');
		}
	}
};
Button.prototype = new Item();
Button.prototype.category_id = 0;
Button.prototype.project_id = 0;
Button.prototype.x = 0;
Button.prototype.y = 0;
Button.prototype.content_x = 0;
Button.prototype.content_y = 0;
Button.prototype.content_width = 1;
Button.prototype.content_height = 1;
Button.prototype.interactive = 0;
Button.prototype.link = "";
Button.prototype.link_enable = false;
Button.prototype.text = "";
Button.prototype.text_enable = false;
Button.prototype.img = "";
Button.prototype.img_title = "";
Button.prototype.img_enable = false;
Button.prototype.lightbox_enable = false;
Button.prototype.img_delete = false;

/**
 * Checks if all the mandatory inputs for a updating/saving a button are correct. 
 */
Button.prototype.check = function() {
	getButtons().hideErrorMessages();
	var isValid = true;
	var btn_alias = $('#btn_alias').val() == '' ? false : true;
	var btn_img = $('#btn_img_path').val() == '' ? false : true;
	var btn_img_enable = $('#btn_img_enable').is(':checked');
	var btn_text = $('#btn_text').val() == '' ? false : true;
	var btn_text_enable = $('#btn_text_enable').is(':checked');
	var btn_link = $('#btn_link').val() == '' ? false : true;
	var btn_link_enable = $('#btn_link_enable').is(':checked');
	if (!btn_alias) {
		isValid = false;
		$('#btn_alias').showError('Alias darf nicht leer sein!');
	}
	/*if (!btn_img && !btn_text && !btn_link) {
		isValid = false;
		$('#btn_content_container').showError('Der Button mus einen Inhalt besitzen (Bild, Text oder Link)!');
		$('#btn_text').showError('Der Button mus einen Inhalt besitzen (Bild, Text oder Link)!');
		$('#btn_link').showError('Der Button mus einen Inhalt besitzen (Bild, Text oder Link)!');
	} else {
		if (btn_img && !btn_img_enable && !btn_text_enable && !btn_link_enable) {
			isValid = false;
			$('#btn_img_enable').showError('Bild nicht aktiviert!');
		}
		if (btn_text && !btn_text_enable && !btn_img_enable && !btn_link_enable) {
			isValid = false;
			$('#btn_text_enable').showError('Text nicht aktiviert!');
		}
		if (btn_link && !btn_link_enable && !btn_img_enable && !btn_text_enable) {
			isValid = false;
			$('#btn_link_enable').showError('Link nicht aktiviert!');
		}
	}*/
	return isValid;
};



/* =========================================================================================================================
 * ############################################        Project        ######################################################
 * =========================================================================================================================
 */


/**
 * The Project Object
 * @param vars object providing the project properties (loaded from the database)
 * @return
 */
function Project(vars){
	if (vars != null) {
		try {
			Item.call(this, vars.prefix, vars.id, vars.type, vars.basename, vars.path, vars.label, vars.alias, vars.thumb, vars.thumb_enable, false, vars.item_class);
			this.category_id = parseInt(vars.category_id);
			this.position 	= parseInt(vars.position);
			this.link			= vars.link;
			this.link_enable	= vars.link_enable;
		} catch(e) {
			if(debug) alert('Initialization of Project failed, missing or wrong parameter! ('+e+')');
		}
	} else {
		try {
			Item.call(this,
					'prj',
					0,
					"project",
					getCategories().currentItem().alias +'_'+$('#prj_alias').val(),
					getCategories().currentItem().alias +'/'+$('#prj_alias').val()+'/',
					'',
					$('#prj_alias').val(),
					'',
					false,
					false,
					'');
			this.category_id = getCategories().currentItem().id;
			this.position 	= 0;
		} catch (e) {
			if(debug) alert('Initialization of new empty Project failed, missing or wrong parameter! ('+e+')');
		}
	}
};

Project.prototype = new Item();
Project.prototype.category_id = 0;
Project.prototype.position = 0;
Project.prototype.link = "";
Project.prototype.link_enable = false;

/**
 * Loads the project's children.
 */
Project.prototype.loadChilds = function() {
	getButtons().load({prefix: getButtons().prefix, ctg_id: this.category_id, prj_id: this.id}, null, false);
};
/**
 * Checks if all the mandatory inputs for a updating/saving a project are correct. 
 */
Project.prototype.check = function() {
	getProjects().hideErrorMessages();
	var isValid = true;
	var prj_alias = $('#prj_alias').val() == '' ? false : true;
	var prj_label = $('#prj_label').val() == '' ? false : true;
	var prj_thumb = $('#prj_thumb_path').val() == '' ? false : true;
	var prj_thumb_enable = $('#prj_thumb_enable').is(':checked');
	var prj_link = $('#prj_link').val() == '' ? false : true;
	var prj_link_enable = $('#prj_link_enable').is(':checked');
	if (!prj_alias) {
		isValid = false;
		$('#'+this.prefix+'_alias').showError('Alias darf nicht leer sein!');
	}
	if (!prj_label && !prj_thumb) {
			isValid = false;
			$('#'+this.prefix+'_label').showError('Ohne Thumbnail ist ein Label notwendig!');
			$('#'+this.prefix+'_thumb_container').showError('Kein Label erfordert ein Thumbnail!');
	} else if (prj_thumb && !prj_thumb_enable) {
			isValid = false;
			$('#'+this.prefix+'_label').showError('Ohne Thumbnail ist ein Label notwendig!');
			$('#'+this.prefix+'_thumb_enable').showError('Ohne Label muss Thumbnail aktiv sein!');
	}
	return isValid;
};



/* =========================================================================================================================
 * ###########################################        Category        ######################################################
 * =========================================================================================================================
 */


/**
 * The Category Object
 * @param vars object providing the category properties (loaded from the database)
 * @return
 */

function Category (vars){
	if (vars != null) {
		try {
			Item.call(this, vars.prefix, vars.id, vars.type, vars.basename, vars.path, vars.label, vars.alias, vars.thumb, vars.thumb_enable, false, vars.item_class);
			this.start_x 	= parseInt(vars.start_x);
			this.start_y 	= parseInt(vars.start_y);
			this.position 	= parseInt(vars.position);
		} catch(e) {
			if(debug) alert('Initialization of Category failed, missing or wrong parameter! ('+e+')');
		}
	} else {
		try {
			Item.call(this,
					'ctg',
					0,
					"category",
					$('#ctg_alias').val(),
					$('#ctg_alias').val()+'/',
					'',
					$('#ctg_alias').val(),
					'',
					false,
					false,
					'');
			this.start_x 	= 0;
			this.start_y 	= 0;
			this.position 	= 0;
		} catch (e) {
			if(debug) alert('Initialization of new empty Category failed, missing or wrong parameter! ('+e+')');
		}
	}
};
Category.prototype = new Item();
Category.prototype.start_x = 0;
Category.prototype.start_y = 0;
Category.prototype.position = 0;

/**
 * Loads the category's children.
 */
Category.prototype.loadChilds = function() {
	getProjects().load({prefix: getProjects().prefix, ctg_id: this.id}, null, false);
	getButtons().load({prefix: getButtons().prefix, ctg_id: this.id}, null, false);
};
/**
 * Checks if all the mandatory inputs for a updating/saving a category are correct. 
 */
Category.prototype.check = function() {
	getCategories().hideErrorMessages();
	var isValid = true;
	var ctg_alias = $('#ctg_alias').val() == '' ? false : true;
	var ctg_label = $('#ctg_label').val() == '' ? false : true;
	var ctg_thumb = $('#ctg_thumb_path').val() == '' ? false : true;
	var ctg_thumb_enable = $('#ctg_thumb_enable').is(':checked');
	if (!ctg_alias) {
		isValid = false;
		$('#'+this.prefix+'_alias').showError('Alias darf nicht leer sein!');
	}
	if (!ctg_label) {
		if (!ctg_thumb || !ctg_thumb_enable) {
			isValid = false;
			$('#'+this.prefix+'_label').showError('Ohne Thumbnail ist ein Label notwendig!');
		}
	}
	if (!ctg_thumb || !ctg_thumb_enable) {
		if (!ctg_label) {
			isValid = false;
			if (!ctg_thumb) {
				$('#'+this.prefix+'_thumb_container').showError('Kein Label erfordert ein Thumbnail!');
			} else {
				$('#'+this.prefix+'_thumb_enable').showError('Ohne Label muss Thumbnail aktiv sein!');
			}
		}
	}
	return isValid;
};


/* =========================================================================================================================
 * ###############################################        Item        ######################################################
 * =========================================================================================================================
 */


var imgScaleRatioX = 300/475;
var imgScaleRatioY = 250/395;


function Item(prefix, id, type, basename, path, label, alias, thumb, thumb_enable, thumb_delete, item_class){
	try {
		this.prefix 		= prefix;
		this.id 			= parseInt(id);
		this.type 			= type;
		this.basename 		= basename;
		this.path 			= path;
		this.label 			= label;
		this.alias 			= alias;
		if (thumb != null && thumb != '')
			this.thumb		= siteRoot+thumb;
		this.thumb_enable 	= thumb_enable;
		this.thumb_delete 	= thumb_delete;
		this.item_class		= item_class;
	} catch (e) {
		if(debug) alert('Initialization of new Item failed, missing or wrong '
				+'parameter! ('+e+')');
	}
};
Item.prototype.prefix = "";
Item.prototype.id = 0;
Item.prototype.type = "";
Item.prototype.basename = "";
Item.prototype.path = "";
Item.prototype.label = "";
Item.prototype.alias = "";
Item.prototype.thumb = "";
Item.prototype.thumb_enable = false;
Item.prototype.thumb_delete = false;
Item.prototype.item_class = "";

Item.prototype.encodeToJSON = function(){
	return JSON.stringify(this);
};
Item.prototype.select = function(event) {
	this.show();
};
/**
 * Loads the dedicated children of the item
 */
Item.prototype.loadChilds = function() {};
/**
 * Shows item properties in the corresponding form elements.
 */
Item.prototype.show = function(){
	try {
		for (key in this) {
			switch (key) {
			case 'thumb':
				if (this[key] != null && this[key] != '') {
					$('#'+this.prefix+'_'+key).attr('src',
							this[key]+'?'+Math.floor(Math.random()*1001));
					$('#'+this.prefix+'_'+key).attr('alt', this[key]);
					$('#'+this.prefix+'_'+key).attr('title', this[key]);
					$('#'+this.prefix+'_thumb_delete_btn').removeAttr("disabled");
					$('#'+this.prefix+'_thumb_enable').removeAttr("disabled");
				} else {
					$('#'+this.prefix+'_'+key).attr('src', 
										noImage+'?'
										+Math.floor(Math.random()*1001));
					$('#'+this.prefix+'_'+key).attr('alt', 'Kein Bild vorhanden.');
					$('#'+this.prefix+'_'+key).attr('title', 'Kein Bild vorhanden.');
					$('#'+this.prefix+'_thumb_delete_btn').attr("disabled", "disabled");
					$('#'+this.prefix+'_thumb_enable').attr("disabled", "disabled");
				}
				$('#'+this.prefix+'_thumb_path').val(this[key].replace(siteRoot, ''));
				break;
			case 'img':
				if (this[key] != null && this[key] != '') {
					var width = Math.abs(Math.round(
							(this.content_width*80-5)*imgScaleRatioX));
					var height = Math.abs(Math.round(
							(this.content_height*80-5)*imgScaleRatioY));
					//var marginLeft = Math.abs(Math.round(
					//		(this.content_x*80)*imgScaleRatioX));
					//var marginTop = Math.abs(Math.round(
					//		(this.content_y*80)*imgScaleRatioY));
					$('#'+this.prefix+'_'+key)
							.attr('width', width)
							.attr('height', height)
							//.css({
								//marginLeft: marginLeft+'px',
								//marginTop: marginTop+'px'
							//})
							.attr('src',
							preview_filename(this[key])+'?'+Math.floor(Math.random()*1001));
					$('#'+this.prefix+'_'+key).attr('alt', this[key]);
					$('#'+this.prefix+'_'+key).attr('title', this[key]);
					$('#'+this.prefix+'_img_delete_btn').removeAttr("disabled");
					$('#'+this.prefix+'_img_enable').removeAttr("disabled");
				} else {
					$('#'+this.prefix+'_'+key).attr('src', '');
					$('#'+this.prefix+'_'+key).attr('alt', '');
					$('#'+this.prefix+'_'+key).attr('title', '');
					$('#'+this.prefix+'_img_delete_btn').attr("disabled", "disabled");
					$('#'+this.prefix+'_img_enable').attr("disabled", "disabled");
				}
				$('#'+this.prefix+'_img_path').val(this[key].replace(siteRoot, ''));
				break;
			case 'img_title':
				$('#'+this.prefix+'_img_title').val(this[key]);
				break;
			case 'interactive':
				$('#'+this.prefix+'_'+key).val(Number(this[key]));
				break;
			case 'text':
				if (this[key] == null || this[key] == '') {
					$('#'+this.prefix+'_text_enable').attr("disabled", "disabled");
				} else {
					$('#'+this.prefix+'_text_enable').removeAttr("disabled");
				}
				$('#'+this.prefix+'_text').val(this[key]);
				break;
			case 'link':
				if (this[key] == null || this[key] == '') {
					$('#'+this.prefix+'_link_enable').attr("disabled", "disabled");
				} else {
					$('#'+this.prefix+'_link_enable').removeAttr("disabled");
				}
				$('#'+this.prefix+'_link').val(this[key]);
				break;
			default:
				if($('#'+this.prefix+'_'+key).length > 0) {
					switch (typeof this[key]) {
						case 'number':
							$('#'+this.prefix+'_'+key).val(this[key]);
							break;
						case 'boolean':
							$('#'+this.prefix+'_'+key).attr('checked', this[key]);
							break;
						case 'string':
							$('#'+this.prefix+'_'+key).val(this[key]);
							break;
					}
				}
			}
		}
		if(this.type == 'button') {
			$('#btn_btn_dummy').css({
				width: Math.abs(Math.round(
						73*imgScaleRatioX)),
				height: Math.abs(Math.round(
						73*imgScaleRatioY)),
				marginLeft: Math.abs(Math.round(
						(this.x*80)*imgScaleRatioX)),
				marginTop: Math.abs(Math.round(
						(this.y*80)*imgScaleRatioY))
			}).html(this.alias).show();
			$('#btn_content_dummy').css({
				marginLeft: Math.abs(Math.round(
						(this.content_x*80)*imgScaleRatioX)),
				marginTop: Math.abs(Math.round(
						(this.content_y*80)*imgScaleRatioY)),
				width: Math.abs(Math.round(
						(this.content_width*80-7)*imgScaleRatioX)),
				height: Math.abs(Math.round(
						(this.content_height*80-7)*imgScaleRatioY))
			}).show();
			//showing other btn dummies
			$('#btn_other_btn_dummies').empty();
			var i = 0;
			for (key2 in getButtons().items) {
				var item = getButtons().items[key2];
				if (this.id != item.id) {
					var width = Math.abs(Math.round(73*imgScaleRatioX));
					var height = Math.abs(Math.round(73*imgScaleRatioY));
					var marginLeft = Math.abs(Math.round(item.x*80)*imgScaleRatioX);
					var marginTop = Math.abs(Math.round(item.y*80)*imgScaleRatioY);
							
					var btnString = "<div id='btn_btn_dummy_"+i+"' class='btn_dummy_other' style='" +
									"top: "+marginTop+"px; " +
									"left: "+marginLeft+"px; " +
									"width: "+width+"px; " +
									"height: "+height+"px; " +
									"z-index: 99;'>"+item.alias+"</div>";
					$('#btn_other_btn_dummies').append(btnString);
				}
				i++;
			}
		}
		if(this.type == 'category' && this.id == 0) {
			$('#btn_y').append('<option value="5">6</option>');
			$('#btn_content_y').append('<option value="5">6</option>');
			$('#btn_content_height').append('<option value="6">6</option>');
		} else if(this.type != 'button') {
			$('#btn_y option[value=5]').remove();
			$('#btn_content_y option[value=5]').remove();
			$('#btn_content_height option[value=6]').remove();
		}
		this.check();
	} catch (e) {
		if(debug) alert('show of ' + key + ' failed, error: ' + e);
	}
	this.loadChilds();
};
Item.prototype.assignValues = function(){
	try {
		for(key in this) {
			switch (key) {
				case 'thumb':
					this[key] = $('#'+this.prefix+'_'+key+'_path').val();
					break;
				case 'img':
					this[key] = $('#'+this.prefix+'_'+key+'_path').val();
					break;
				case 'interactive':
					this[key] = $('#'+this.prefix+'_'+key).val();
					break;
				default:
					if($('#'+this.prefix+'_'+key).length > 0) {
						switch (typeof this[key]) {
							case 'number':
								this[key] = parseInt($('#'+this.prefix+'_'+key).val());
								break;
							case 'string':
								this[key] = $('#'+this.prefix+'_'+key).val();
								break;
							case 'boolean':
								this[key] = $('#'+this.prefix+'_'+key).is(':checked');
								break;
						}
					}
			}
		}
		return true;
	} catch (e) {
		if(debug) alert('assign of ' + key + ' failed, error: ' +e);
		return false;
	}
};
/**
 * Checks if all the mandatory inputs for a updating/saving an item are correct. 
 */
Item.prototype.check = function() {};
Item.prototype.resetItem = function(){
	this.show();
};


/* =========================================================================================================================
 * ####################################        Item Container         ######################################################
 * =========================================================================================================================
 */


/**
 * ItemContainer Klasse
 * @param type 				String - Typ des ItemContainers (preface, category, project oder button)
 * @param prefix 			String - Prefix der MySQL Datensätze die mit dem Containertyp verknüpft sind (ctg, prj oder btn)
 * @param urlLoad 			String - URL des php Script welches die Inhalte des Containers aus der Datenbank lädt
 * @param urlSave 			String - URL des php Script welches die Inhalte des Containers in die Datenbank speichert
 * @param urlNew 			String - URL des php Script welches die ein neues Objekt in der Datenbank anlegt
 * @param urlDelete			String - URL des php Script welches das aktuelle Objekt in der Datenbank löscht
 * @param urlDeleteThumb	String - URL des php Script welches das Thumbnail des aktuelle Objekts in der Datenbank und auf dem Datenträger löscht
 * @param urlDeleteImage	String - URL des php Script welches das Bild des aktuelle Objekts in der Datenbank und auf dem Datenträger löscht
 */
function ItemContainer(type, prefix, urlLoad, urlSave, urlNew, urlDelete, urlDeleteThumb, urlDeleteImage ) {
	try {
		this.type = type;
		this.prefix = prefix;
		this.item_selector = '#select_'+type;
		this.position_selector = '#'+prefix+'_position';
		this.form = '#form_'+type;
		this.urlLoad = urlLoad;
		this.urlSave = urlSave;
		this.urlNew = urlNew;
		this.urlDelete = urlDelete;
		this.urlDeleteThumb = urlDeleteThumb;
		this.urlDeleteImage = urlDeleteImage;
		this.items = null;
		var handle = this;
		/*
		 * #########################################################################
		 * ########################### Thumb Uploader ##############################
		 * #########################################################################
		 */
		this.progressBarThumb = $('#'+this.prefix+'_thumb_upload_progress_bar').progressbar({});
		this.thumbUploader = $('#'+this.prefix+'_thumb_upload_container').swfupload({
			upload_url: libPathPHP+"uploadThumbToCrop.php",
			file_size_limit : maxImgSize,
			file_types : "*.jpg;*.png;*.gif;*.jpeg",
			file_types_description : "Web Image Files",
			file_upload_limit : "0",
			flash_url : libPathJS+"swfupload.swf",
			button_image_url : 'css/images/swfupload.png',
			button_width : 61,
			button_height : 22,
			button_placeholder : $('#'+this.prefix+'_thumb_upload_btn')[0],
			debug: false
			})
			.bind('swfuploadLoaded', function(event){})
			.bind('fileQueued', function(event, file){
				$(this).swfupload('startUpload');
			})
			.bind('fileQueueError', function(event, file, errorCode, message){
				if(errorCode == SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED)
					alert(message);
				if(errorCode == SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT)
					alert('Fehler: Die Datei ist größer als '+maxImgSize);
				if(errorCode == SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE)
					alert(message);
				if(errorCode == SWFUpload.QUEUE_ERROR.INVALID_FILETYPE)
					alert(message);
			})
			.bind('fileDialogStart', function(event){})
			.bind('fileDialogComplete', function(event, numFilesSelected, numFilesQueued){})
			.bind('uploadStart', function(event, file){
			})
			.bind('uploadProgress', function(event, file, bytesLoaded, bytesTotal){
				handle.progressBarThumb.progressbar('value', (bytesLoaded/bytesTotal)*100);
				if (bytesLoaded == bytesTotal) {
					// open the crop dialog and start the upload since it's queued
					handle.showCropDialog();
				}
			})
			.bind('uploadSuccess', function(event, file, serverData){
				handle.startCrop(file, serverData);
				handle.progressBarThumb.progressbar('value', 0);
			})
			.bind('uploadComplete', function(event, file){})
			.bind('uploadError', function(event, file, errorCode, message){
				if(errorCode == SWFUpload.UPLOAD_ERROR.HTTP_ERROR)
					alert(message);
				if(errorCode == SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL)
					alert(message);
				if(errorCode == SWFUpload.UPLOAD_ERROR.IO_ERROR)
					alert(message);
				if(errorCode == SWFUpload.UPLOAD_ERROR.SECURITY_ERROR)
					alert(message);
				if(errorCode == SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED)
					alert(message);
				if(errorCode == SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED)
					alert(message);
				if(errorCode == SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND)
					alert(message);
				if(errorCode == SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED)
					alert(message);
				if(errorCode == SWFUpload.UPLOAD_ERROR.FILE_CANCELLED)
					alert(message);
				if(errorCode == SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED)
					alert(message);
			});
		if (this.type == 'button') {
			/*
			 * #########################################################################
			 * ############################# Image Upload ##############################
			 * #########################################################################
			 */
			this.progressBarImage = $('#btn_img_upload_progress_bar').progressbar({});
			this.imageUploader = $('#btn_img_upload_container').swfupload({
				upload_url: libPathPHP+"uploadImage.php",
				file_size_limit : maxImgSize,
				file_types : "*.jpg;*.png;*.gif;*.jpeg;*.pdf",
				file_types_description : "Web Image Files",
				file_upload_limit : "0",
				flash_url : libPathJS+"swfupload.swf",
				button_image_url : 'css/images/swfupload.png',
				button_width : 61,
				button_height : 22,
				button_placeholder : $('#btn_img_upload_btn')[0],
				debug: false,
				post_params: {
					filename : '', 
					folder: '',
					width: 1,
					height: 1,
					quality: 100,
				}
				})
				.bind('swfuploadLoaded', function(event){})
				.bind('fileQueued', function(event, file){
					$(this).swfupload('startUpload');
				})
				.bind('fileQueueError', function(event, file, errorCode, message){
					if(errorCode == SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED)
						alert(message);
					if(errorCode == SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT)
						alert('Fehler: Die Datei ist größer als '+maxImgSize);
					if(errorCode == SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE)
						alert(message);
					if(errorCode == SWFUpload.QUEUE_ERROR.INVALID_FILETYPE)
						alert(message);
				})
				.bind('fileDialogStart', function(event){})
				.bind('fileDialogComplete', function(event, numFilesSelected, numFilesQueued){
					$(this).swfupload('setPostParams', {
						filename : getButtons().currentItem().basename, 
						folder: getButtons().currentItem().path,
						width: parseInt($('#btn_content_width').val()),
						height: parseInt($('#btn_content_height').val()),
						quality: $('#btn_quality').val() == '' ? '100' : $('#btn_quality').val()
					});
				})
				.bind('uploadStart', function(event, file){})
				.bind('uploadProgress', function(event, file, bytesLoaded, bytesTotal){
					handle.progressBarImage.progressbar('value', (bytesLoaded/bytesTotal)*100);
					if (bytesLoaded == bytesTotal) {
						// open the crop dialog and start the upload since it's queued
						handle.showCropDialog();
					}
				})
				.bind('uploadSuccess', function(event, file, serverData){
					handle.startCrop(file, serverData);
					handle.progressBarImage.progressbar('value', 0);
				})
				.bind('uploadComplete', function(event, file){
				})
				.bind('uploadError', function(event, file, errorCode, message){
					if(errorCode == SWFUpload.UPLOAD_ERROR.HTTP_ERROR)
						alert(message);
					if(errorCode == SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL)
						alert(message);
					if(errorCode == SWFUpload.UPLOAD_ERROR.IO_ERROR)
						alert(message);
					if(errorCode == SWFUpload.UPLOAD_ERROR.SECURITY_ERROR)
						alert(message);
					if(errorCode == SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED)
						alert(message);
					if(errorCode == SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED)
						alert(message);
					if(errorCode == SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND)
						alert(message);
					if(errorCode == SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED)
						alert(message);
					if(errorCode == SWFUpload.UPLOAD_ERROR.FILE_CANCELLED)
						alert(message);
					if(errorCode == SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED)
						alert(message);
				});
			/*
			 * #########################################################################
			 * ############################# Text Editor ###############################
			 * #########################################################################
			 */
				this.textEditor = $('#btn_text').tinymce({
					// Location of TinyMCE script
					script_url : 'lib/js/tinymce/jscripts/tiny_mce/tiny_mce.js',
		
					// General options
					theme : "advanced",
					plugins : "style,table,save,advhr,advlink,inlinepopups,insertdatetime,preview,searchreplace,contextmenu,paste,fullscreen,visualchars,nonbreaking,xhtmlxtras",
		
					// Theme options
					theme_advanced_buttons1 : "save,|,undo,redo,|,cut,copy,paste,pastetext,pasteword,|,search,replace,|,cleanup,code,|,fullscreen,|,help",
					theme_advanced_buttons2 : "formatselect,fontselect,fontsizeselect,|,bullist,numlist,|,outdent,indent,blockquote",
					theme_advanced_buttons3 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,removeformat,visualaid,|,sub,sup,|,charmap,advhr",
					theme_advanced_buttons4 : "link,unlink,anchor,|,preview,|,forecolor,backcolor,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking",
					theme_advanced_toolbar_location : "top",
					theme_advanced_toolbar_align : "left",
					theme_advanced_statusbar_location : "bottom",
					theme_advanced_resizing : true,
					
					apply_source_formatting : false,
					
					// Example content CSS (should be your site CSS)
					content_css : "../css/style.css",
		
					// Drop lists for link/image/media/template dialogs
					template_external_list_url : "lists/template_list.js",
					external_link_list_url : "lists/link_list.js",
					external_image_list_url : "lists/image_list.js",
					media_external_list_url : "lists/media_list.js",
		
					// Replace values for the template plugin
					template_replace_values : {
						username : "Some User",
						staffid : "991234"
					}
				});
		}
	} catch(e) {
		if(debug) alert('Initialization of new ItemContainer failed, missing or wrong parameter! ('+e+')');
	}
};
ItemContainer.prototype.type = null;
ItemContainer.prototype.prefix = null;
ItemContainer.prototype.item_selector = null;
ItemContainer.prototype.position_selector = null;
ItemContainer.prototype.form = null;
ItemContainer.prototype.urlLoad = null;
ItemContainer.prototype.urlSave = null;
ItemContainer.prototype.urlNew = null;
ItemContainer.prototype.urlDelete = null;
ItemContainer.prototype.urlDeleteThumb = null;
ItemContainer.prototype.urlDeleteImage = null;
ItemContainer.prototype.items = null;
ItemContainer.prototype.thumbUploader = null;
ItemContainer.prototype.imageUploader = null;
ItemContainer.prototype.textEditor = null;
ItemContainer.prototype.progressBarThumb = null;
ItemContainer.prototype.progressBarImage = null;

ItemContainer.prototype.getInstance = function() {
	switch(this.type) {
	case 'category':
		return getCategories();
	case 'project':
		return getProjects();
	case 'button':
		return getButtons();
	}
};
ItemContainer.prototype.length = function(){
	if (this.items != null) {
		var i = 0;
		for (key in this.items) {
			i++;
		}
		return i;
	} else {
		return 0;
	}
};
ItemContainer.prototype.currentItem = function(){
	if(this.items[this[0].value] != null) {
		return this.items[this[0].value];
	} else {
		return null;
	}
};
ItemContainer.prototype.prevItem = function(){
	return this.items[this.prevOption().val()];
};
ItemContainer.prototype.nextItem = function(){
	return this.item[this.nextOption().val()];
};
ItemContainer.prototype.currentOption = function(){
	return $(this.item_selector+' option:selected');
};
ItemContainer.prototype.prevOption = function(){
	return $(this.item_selector + ' option:selected').prev();
};
ItemContainer.prototype.nextOption = function(){
	return $(this.item_selector + ' option:selected').next();
};
ItemContainer.prototype.change = function(event) {
	//if (this.currentItem() != null && this.currentItem().id != 0) {
		this.currentItem().select(event);
	//}
};
ItemContainer.prototype.hideErrorMessages = function () {
	$(this.form).hideErrorMessages();
};
ItemContainer.prototype.clearFormElements = function (empty_selector) {
	if(empty_selector) {
		$(this.item_selector).empty();
	}
	$(this.form).clearForm();
};
ItemContainer.prototype.preSelect = function(preSelection, autoSelect){
	//wenn übergeben, preselected item fokussieren
	if (preSelection != null) {
		this[0].selectedIndex = this.items[preSelection].position;
		$(this.item_selector).val($(this.item_selector +
				' option[value="'+preSelection+'"]').val()).focus().change();
	//anderfalls, wenn autoSelect = true, das erste element fokussieren
	} else if (autoSelect) {
		$(this.item_selector).val($(this.item_selector + ' option:first').val())
			.focus().change();
	} else {
		this.clearFormElements(false);
	}
};

ItemContainer.prototype.show = function(preSelection, autoSelect){
	if (this.length() > 0) {
		//die select-box leeren
		$(this.item_selector).empty();
		//falls positions-box vorhanden, diese leeren
		if (this.position_selector != null) {
			$(this.position_selector).empty();
		}
		var i = 0;
		for(key in this.items) {
			//select-box mit optionen füllen 
			$(this.item_selector).append('<option value="'+key+'" >'
					+this.items[key].alias+'</option>'+'\n');
			//optional position-box füllen
			if (this.position_selector != null) {
				$(this.position_selector).append('<option value="'+i+'" >'
						+(i+1)+'</option>'+'\n');
			}
			i++;
		}
		this.preSelect(preSelection, autoSelect);
	} else {
		this.clearFormElements(true);
	}
};
ItemContainer.prototype.fillItems = function(items_temp, preSelection, autoSelect) {
	//index des items im options array des select-elements
	for(key in items_temp) {
		//Die geladenen Objekte erstellen und in items speichern
		switch (this.type) {
		case 'category':
			this.items[key] = new Category(items_temp[key]);
			break;
		case 'project':
			this.items[key] = new Project(items_temp[key]);
			break;
		case 'button':
			this.items[key] = new Button(items_temp[key]);
			break;
		}
	}
	//preface einfügen
	if (this.type == 'category') {
		var preface = {
				type: 'category',
				basename: 'preface',
				path: '/preface/',
				prefix: 'ctg',
				id: 0,
				alias: 'preface',
				label: 'Preface',
				thumb: '',
				thumb_enable: false,
				start_x: 0,
				start_y: 0,
				position: this.length()
		};
		this.items[0] = new Category(preface);
	}
	if (this.length() > 0) {
		this.show(preSelection, autoSelect);
	} else {
		this.clearFormElements(true);
	}
};
/**
 * Lädt Item-Daten aus der Datenbank, instanziiert damit Item-Objekte
 * die im Item-Container-Objekt gespeichert und anschließend angezeigt werden.
 * 
 * @param params 		Parameter Objekt: {prefix, ctg_id und prj_id}
 * @param preSelection	ID des Items das nach dem laden ausgewählt werden soll.
 * @param autoSelect	Automatische auswahl des ersten Items wenn true
 * @return
 */
ItemContainer.prototype.load = function(params, preSelection, autoSelect) {
	this.items = new Object();
	var handle = this;
	$.getJSON(this.urlLoad, params, function(response){
		//wenn Anfrage erfolgreich und items nicht leer
		if(response.result && response.items != null) {
			handle.fillItems(response.items, preSelection, autoSelect);
		} else {
			if(debug) alert('load ' + handle.type + ' failed:\n'
					+ 'error: ' +response.error +"\n"
					+ 'items: ' +response.items +"\n"
					+ 'itemContainer: ' +($(handle.item_selector).length > 0));
		}
	});
};

ItemContainer.prototype.newItem = function() {
	var item = null;
	switch (this.type) {
	case 'category':
		var item = new Category();
		break;
	case 'project':
		var item = new Project();
		break;
	case 'button':
		var item = new Button();
		break;
	}
	if (this.items == null) {
		this.items = new Object();
		this.items[item.id] = item;
	} else {
		this.items[item.id] = item;
	}
	item.position = this.length()-1;
	this.show(item.id, false);
};

/**
 * Saves the current selected item to the database and reloads 
 * all items afterwards.
 * 
 * @return
 */
ItemContainer.prototype.saveItem = function() {
	if (this.currentItem() != null /*&& this.currentItem().id != 0*/) {
		if(this.currentItem().check()){
			if(this.currentItem().assignValues()) {
				var prefix = this.prefix;
				var ctg_id = this.currentItem().category_id;
				var prj_id = this.currentItem().project_id;
				var handle = this;
				if(this.currentItem().id > 0) {
					//existierendes Item updaten
					$.post(this.urlSave,
							{data: this.currentItem().encodeToJSON()},
							function(response) {
								if(response.result) {
									handle.load({prefix: prefix,
										ctg_id: ctg_id,
										prj_id: prj_id},
										response.id, false);
									alert(handle.type+' gespeichert.');
								} else {
									alert('Save '+handle.type+' failed: '+response.error);
								}
							}, 'json');
				} else {
					//neues Item speichern
					$.post(this.urlNew,
							{data: this.currentItem().encodeToJSON()},
							function(response) {
								if(response.result) {
									handle.load({prefix: prefix,
										ctg_id: ctg_id,
										prj_id: prj_id},
										response.id, false);
									alert(handle.type+' gespeichert.');
								} else {
									alert('Save new '+handle.type+' failed: '+response.error);
								}
							}, 'json');
				}
			}
		} else {
			alert("Eines der rot markierten Felder ausfüllen!");
		}
	}
};
/**
 * Setzt das ausgewählte Item aus seinen zuletzt gespeicherten Stand zurück.
 * 
 * @return
 */
ItemContainer.prototype.resetItem = function(){
	if (this.currentItem() != null && this.currentItem().id != 0) {
		this.currentItem().resetItem();
	}
};
/**
 * Löscht das ausgewählte Item.
 * Alle Daten des Items, die Daten der Kind-Items sowie ihre zugehörigen
 * Bild-Dateien werden aus der Datenbank und vom Datenträger gelöscht.
 * 
 * @return
 */
ItemContainer.prototype.deleteItem = function(){
	if (this.currentItem() != null && this.currentItem().id != 0) {
		if(confirm(this.type+' wirklich löschen?')) {
			var prefix = this.prefix;
			var id = this.currentItem().id;
			if(this.type == 'category') {
				var ctg_id = this.currentItem().id;
			} else {
				var ctg_id = this.currentItem().category_id;
			}
			var prj_id = this.currentItem().project_id;
			var path = this.currentItem().path;
			if (this.currentItem().position != null)
				var position = this.currentItem().position;
			else
				var position = null;
			var selectAfter = null;
			var nextOption = $(this.nextOption()).val();
			if (nextOption != null) {
				var selectAfter = nextOption;
			} else {
				var selectAfter = $(this.prevOption()).val();
			}
			var handle = this;
			
			$.getJSON(this.urlDelete, {prefix: prefix, id: id, ctg_id: ctg_id, path: path, position: position}, function(response){
				if(response.result) {
					handle.load({prefix: prefix, ctg_id: ctg_id, prj_id: prj_id}, selectAfter, false);
					var errorString = 'Löschen erfolgreich:\n';
					if(response.result_files) 
						errorString += '- verknüpfte Dateien gelöscht.\n';
					else errorString += '- keine verknüpften Dateien gefunden.\n';
					if(response.result_categories)
						errorString += '- Kategorie gelöscht.\n';
					else errorString += '- keine Kategorie gelöscht.\n';
					if(response.result_projects)
						errorString += '- Projekte gelöscht.\n';
					else errorString += '- keine Projekte gelöscht.\n';
					if(response.result_buttons)
						errorString += '- Buttons gelöscht.\n';
					else errorString += '- keine Buttons gelöscht.\n';
					if(debug) alert(errorString);
				} else {
					var errorString = 'Delete '+handle.type+' failed: '+response.error+'\n';
					if(response.error_files != null) 
						errorString += 'Error while deleting associated files: ' + response.error_files+'\n';
					if(response.error_categories != null)
						errorString += 'Error while deleting categories: ' + response.error_categories+'\n';
					if(response.error_projects != null)
						errorString += 'Error while deleting projects: ' + response.error_projects+'\n';
					if(response.error_buttons != null)
						errorString += 'Error while deleting buttons: ' + response.error_buttons+'\n';
					if(debug) alert(errorString);
				}
			});
		}
	}
};
/**
 * Löscht das Thumbnail des ausgewählten Items.
 * 
 * @return
 */
ItemContainer.prototype.deleteThumb = function(){
	if (this.currentItem() != null && this.currentItem().id != 0) {
		if (this.currentItem().thumb != null && this.currentItem().thumb != '') {
			if(confirm('Thumb wirklich löschen?')) {
				var id = this.currentItem().id;
				var ctg_id = this.currentItem().category_id;
				var prj_id = this.currentItem().project_id;
				var prefix = this.prefix;
				var path = this.currentItem().thumb.replace(siteRoot, '');
				var handle = this;
				if (this.urlDeleteThumb != null) {
					$.getJSON(this.urlDeleteThumb, {prefix: prefix, id: id, path: path}, function(response){
						if(response.result) {
							handle.load({prefix: prefix, ctg_id: ctg_id, prj_id: prj_id}, id, false);
							var errorString = 'Thumbnail gelöscht\n';
							alert(errorString);
						} else {
							var errorString = 'Thumbnail nicht gelöscht: '+response.error+'\n';
							alert(errorString);
						}
					});
				}
			}
		} else {
			alert('Es existiert kein Thumbnail!');
		}
	} else {
	}
};
/**
 * Löscht das Bild des ausgewählten Items.
 * 
 * @return
 */
ItemContainer.prototype.deleteImage = function(){
	if (this.currentItem() != null && this.currentItem().id != 0) {
		if (this.currentItem().img != null && this.currentItem().img != '') {
			if(confirm('Bild wirklich löschen?')) {
				var id = this.currentItem().id;
				var ctg_id = this.currentItem().category_id;
				var prj_id = this.currentItem().project_id;
				var prefix = this.prefix;
				var path = this.currentItem().img.replace(siteRoot, '');
				var handle = this;
				if (this.urlDeleteImage != null) {
					$.getJSON(this.urlDeleteImage, {prefix: prefix, id: id, path: path}, function(response){
						if(response.result) {
							handle.load({prefix: prefix, ctg_id: ctg_id, prj_id: prj_id}, id, false);
							var errorString = 'Bild gelöscht\n';
							alert(errorString);
						} else {
							var errorString = 'Bild nicht gelöscht: '+response.error+'\n';
							alert(errorString);
						}
					});
				}
			}
		} else {
			alert('Es existiert kein Bild!');
		}
	} else {
	}
};
/**
 * Speichert für das ausgewählte Item ein Thumbnail.
 * 
 * @return
 */
ItemContainer.prototype.saveThumb = function() {
	var path = this.currentItem().path;
	var handle = this;
	if($('.jcrop-holder').length > 0) {
		if(tempImagePath != '') {
			$.post(libPathPHP+"saveThumb.php",
					{file: tempImagePath,
					folder: path,
					crop_x: $('#img_crop_x').val(),
					crop_y: $('#img_crop_y').val(),
					crop_w: $('#img_crop_w').val(),
					crop_h: $('#img_crop_h').val()},
					function(response){
						if (response.result) {
							$('#'+handle.prefix+'_thumb_path').val(response.pathname);
							$('#'+handle.prefix+'_thumb').attr('src',
									siteRoot+response.pathname+'?'+Math.floor(Math.random()*1001));
							$('#'+handle.prefix+'_thumb_enable').attr('checked', true);
							handle.saveItem();
						} else {
							alert('Fehler beim Erstellen des Thumbnails: '+response.error);
						}
					},
					"json");
		} else {
			alert('Kein Bild hochgeladen');
		}
	}
};
/**
 * Speichert für das ausgewählte Item ein VorschauBild für das Grid.
 * 
 * @return
 */
ItemContainer.prototype.savePreview = function() {
	var path = this.currentItem().path;
	var handle = this;
	if($('.jcrop-holder').length > 0) {
		if(tempImagePath != '') {
			$.post(libPathPHP+"savePreview.php",
					{file: tempImagePath,
					folder: path,
					image_width: parseInt($('#btn_content_width').val())*80-5,
					image_height: parseInt($('#btn_content_height').val())*80-5,
					crop_x: $('#img_crop_x').val(),
					crop_y: $('#img_crop_y').val(),
					crop_w: $('#img_crop_w').val(),
					crop_h: $('#img_crop_h').val()},
					function(response){
						if (response.result) {
							$('#'+handle.prefix+'_img_path').val(response.filepath);
							$('#'+handle.prefix+'_img').attr('src',
									siteRoot+response.previepath+'?'+Math.floor(Math.random()*1001));
							$('#'+handle.prefix+'_img_enable').attr('checked', true);
							$('#'+handle.prefix+'_lightbox_enable').attr('checked', true);
							handle.saveItem();
						} else {
							alert('Fehler beim Erstellen der Bildvorschau: '+response.error);
						}
					},
					"json");
		} else {
			alert('Kein Bild hochgeladen');
		}
	}
};
ItemContainer.prototype.paintBtnDummy = function (x, y, width, height) {
	$('#btn_btn_dummy').css({
		width: Math.abs(Math.round(
				73*imgScaleRatioX)),
		height: Math.abs(Math.round(
				73*imgScaleRatioY)),
		marginLeft: Math.abs(Math.round(
				(this.x*80)*imgScaleRatioX)),
		marginTop: Math.abs(Math.round(
				(this.y*80)*imgScaleRatioY))
	}).show();
	$('#btn_content_dummy').css({
		marginLeft: Math.abs(Math.round(
				(this.content_x*80)*imgScaleRatioX)),
		marginTop: Math.abs(Math.round(
				(this.content_y*80)*imgScaleRatioY)),
		width: Math.abs(Math.round(
				(this.content_width*80-7)*imgScaleRatioX)),
		height: Math.abs(Math.round(
				(this.content_height*80-7)*imgScaleRatioY))
	}).show();
};
ItemContainer.prototype.updatePreview = function() {
	if(this.type == 'button') {
		$('#btn_btn_dummy').css({
			width: Math.abs(Math.round(
					73*imgScaleRatioX)),
			height: Math.abs(Math.round(
					73*imgScaleRatioY)),
			marginLeft: Math.abs(Math.round(
					($('#'+this.prefix+'_x').val()*80)*imgScaleRatioX)),
			marginTop: Math.abs(Math.round(
					($('#'+this.prefix+'_y').val()*80)*imgScaleRatioY))
		}).show();
		$('#btn_content_dummy').css({
			marginLeft: Math.abs(Math.round(
					($('#'+this.prefix+'_content_x').val()*80)*imgScaleRatioX)),
			marginTop: Math.abs(Math.round(
					($('#'+this.prefix+'_content_y').val()*80)*imgScaleRatioY)),
			width: Math.abs(Math.round(
					($('#'+this.prefix+'_content_width').val()*80-7)*imgScaleRatioX)),
			height: Math.abs(Math.round(
					($('#'+this.prefix+'_content_height').val()*80-7)*imgScaleRatioY))
		}).show();
		//var marginLeft = Math.abs(Math.round(
		//		($('#'+this.prefix+'_content_x').val()*80)*imgScaleRatioX));
		//var marginTop = Math.abs(Math.round(
		//		($('#'+this.prefix+'_content_y').val()*80)*imgScaleRatioY));
		var width = Math.abs(Math.round(
				($('#'+this.prefix+'_content_width').val()*80-5)*imgScaleRatioX));
		var height = Math.abs(Math.round(
				($('#'+this.prefix+'_content_height').val()*80-7)*imgScaleRatioY));
		$('#'+this.prefix+'_img')
				.attr('width', width)
				.attr('height', height);
				//.css({
				//	marginLeft: marginLeft+'px',
				//	marginTop: marginTop+'px'
				//});*/
	}
};
ItemContainer.prototype.checkAlias = function(newAlias) {
	if (newAlias == '') {
		alert('Bitte einen Alias eingeben!');
		return false;
	}
	for (key in this.items) {
		if (newAlias == this.items[key].alias) {
			alert('Alias existiert bereits! Bitte einen eindeutigen Alias eingeben.');
			return false;
		}
	}
	return true;
};
ItemContainer.prototype.showCropDialog = function() {
	$('#crop_container').addClass('loading');
	resetCrop();
	cropDialog.dialog('open');
	cropDialog.container = this;
};
ItemContainer.prototype.startCrop = function(file, serverData) {
	var response = jQuery.parseJSON(serverData);
	if(response.result){
		$('.swfupload').hide();
		cropDialog.callback = response.callback;
		$('#crop_container').removeClass('loading');
		crop(response, true);
	} else {
		if(debug) alert('Error while uploading image: '+response.response);
	}
};


/* =========================================================================================================================
 * #############################################         Crop         ######################################################
 * =========================================================================================================================
 */

function updateCoords(c) {
	$('#img_crop_x').val(c.x);
	$('#img_crop_y').val(c.y);
	$('#img_crop_w').val(c.w);
	$('#img_crop_h').val(c.h);
};

function doPreview(coords) {
	if (parseInt(coords.w) > 0) {
		var rx = 75 / coords.w;
		var ry = 75 / coords.h;
		$('#crop_img_thumb').css({
			width: Math.round(rx * imgwidth) + 'px',
			height: Math.round(ry * imgheight) + 'px',
			marginLeft: '-' + Math.round(rx * coords.x) + 'px',
			marginTop: '-' + Math.round(ry * coords.y) + 'px'
		});
	}
};
function resetCrop() {
	$("#crop_img_orig").remove();
	$("#crop_img_thumb").remove();
	$(".jcrop-holder").Jcrop("destroy");
	$(".jcrop-holder").remove();
}
function crop(response, crop) {
	if (response.filepath != null && response.filepath != '') {
		var scale_x = response.scale_x;
		var scale_y = response.scale_y;
		var newImg = new Image();
		$(newImg).load().attr('src', siteRoot+response.filepath+'?'+Math.floor(Math.random()*1001))
						.attr('id', 'crop_img_orig');
		imgwidth = response.imagewidth;
		imgheight = response.imageheight;
		$('#crop_container').append(newImg);
		
		if (crop) {
			var aspectRatio = scale_x/scale_y;
			$(newImg).Jcrop({
				aspectRatio: aspectRatio,
				setSelect: [0, 0, scale_x, scale_y],
				//onChange: doPreview,
				//onSelect: doPreview,
				onSelect: updateCoords
			});
			tempImagePath = response.filepath;
		}
	}
};



/* =========================================================================================================================
 * ############################################         Utils         ######################################################
 * =========================================================================================================================
 */

$.fn.clearForm = function() {
	return this.each(function() {
		var type = this.type, tag = this.tagName.toLowerCase();
		if (tag == 'form' || tag == 'fieldset') {
		    $(this).hideErrorMessages();
		    $(this).find('.thumb').each(function(){
		    	this.src = noImage;
		    	this.alt = 'Kein Bild vorhanden.';
		    	this.title = 'Kein Bild vorhanden.';
		    });
		    $(this).find('.img').each(function(){
		    	this.src = '';
		    	this.alt = '';
		    	this.title = '';
		    });
		    $(this).find('#btn_btn_dummy').hide();
		    $(this).find('#btn_content_dummy').hide();
			return $(':input',this).clearForm();
		}
		if (type == 'text' || type == 'password' || type == 'textarea' 
			|| type == 'file' || type == 'hidden')
			this.value = '';
		else if (type == 'checkbox' || type == 'radio')
			this.checked = false;
		else if (tag == 'select') {
			this.selectedIndex = -1;
		}
	});
};
$.fn.showError = function(message){
	if (!$(this).parent().hasClass('error')) {
		$(this).parent().addClass('error').find('label').before('<strong class="message_error">'+message+'</strong>');
	}
};
$.fn.hideErrorMessages = function() {
	$(this).find('.error').removeClass('error');
    $(this).find('.message_error').remove();
};
function preview_filename (file) {
	var filetype = file.substring(file.lastIndexOf('.'));
	var filename = file.substring(0, file.lastIndexOf('.'));
	var preview = filename+'_preview'+filetype;
	return preview;
}


/* =========================================================================================================================
 * ############################################         Admin         ######################################################
 * =========================================================================================================================
 */

var libPathPHP = 'lib/php/';
var libPathJS = 'lib/js/';
var noImage = "css/images/noImage.png";
var imageRoot = 'images/';
var url = location.href;
var urlTemp = url.substring(0, url.lastIndexOf('/'));
var siteRoot = url.substring(0, urlTemp.lastIndexOf('/')+1);

var urlLoad = libPathPHP+'load.php';
var urlSave = libPathPHP+'save.php';
var urlNew = libPathPHP+'new.php';
var urlDelete = libPathPHP+'delete.php';
var urlDeleteThumb = libPathPHP+'deleteThumb.php';
var urlDeleteImage = libPathPHP+'deleteImage.php';

var debug = true;
var categories = null;
var projects = null;
var buttons = null;

var imgwidth = 75;
var imgheight = 75;
var tempImagePath = '';

var maxImgSize = '5MB';

var cropDialog = null;
var alertDialog = null;

var current_container = null;

function getCategories(){
	if(categories == null) {
		categories = $('#select_category');
		var categoryContainer = new ItemContainer('category',
				'ctg',
				urlLoad,
				urlSave,
				urlNew,
				urlDelete,
				urlDeleteThumb,
				null);
		$.extend(categories, categoryContainer);
	}
	return categories;
};

function getProjects(){
	if(projects == null) {
		projects = $('#select_project');
		var projectContainer = new ItemContainer('project',
				'prj',
				urlLoad,
				urlSave,
				urlNew,
				urlDelete,
				urlDeleteThumb,
				null);
		$.extend(projects, projectContainer);
	}
	return projects;
};

function getButtons(){
	if(buttons == null) {
		buttons = $('#select_button');
		var buttonContainer = new ItemContainer('button',
				'btn',
				urlLoad,
				urlSave,
				urlNew,
				urlDelete,
				urlDeleteThumb,
				urlDeleteImage);
		$.extend(buttons, buttonContainer);
	}
	return buttons;
};

function focus(container) {
	switch(container.type) {
		case getCategories.type:
			getProjects.clearFormElements(true);
			getButtons.clearFormElements(true);
			break;
		case getProjects.type:
			getButtons.clearFormElements(true);
			break;
		case getButtons.type:
			break;
		default:
			break;
	}
	current_container = container;
}

/*
 * ############################################################################
 * ################################## Main ####################################
 * ############################################################################
 */

function init() {
	$('.yform').clearForm();
	getCategories();
	getProjects();
	getButtons();
	getCategories().load({prefix: getCategories().prefix}, null, true);
	
	/*
	 * #########################################################################
	 * ############################# Category Buttons ##########################
	 * #########################################################################
	 */
	
	$('#select_category').focus( function() {
		focus(getCategories());
		getCategories().change();
	});
	$('#select_category').change( function() {
		getCategories().change();
	});
	$('#btn_saveCtg').click( function() {
		this.blur();
		getCategories().saveItem();
	});

	// New Category Dialog			
	$('#dialog_newCtg').dialog({
		autoOpen: false,
		width: 250,
		modal: true,
		position: [$('#btn_newCtg').offset().left-40, $('#btn_newCtg').offset().top+50],
		open: function() {
			$('#dialog_newCtg').keyup(function(e) {
			    if (e.keyCode == 13) {
			    	e.stopImmediatePropagation();
			    	e.preventDefault();
			        if (getCategories().checkAlias($('#ctg_new_alias').val())) {
						$('#ctg_alias').val($('#ctg_new_alias').val());
						$('#ctg_new_alias').val('');
						getCategories().newItem();
						$(this).dialog("close");
					}
			    	return false;
			    }
			});
		},
		buttons: {
			"Ok": function() {
				if (getCategories().checkAlias($('#ctg_new_alias').val())) {
					$('#ctg_alias').val($('#ctg_new_alias').val());
					$('#ctg_new_alias').val('');
					getCategories().newItem();
					$(this).dialog("close");
				}
			}, 
			"Cancel": function() {
				$(this).dialog("close");
			} 
		}
	});
	
	$('#btn_newCtg').click( function() {
		this.blur();
		getCategories().clearFormElements(false);
		$('#dialog_newCtg').dialog('open');
	});
	$('#btn_resetCtg').click( function() {
		this.blur();
		$('#select_category').focus().change();
	});
	$('#btn_deleteCtg').click( function() {
		this.blur();
		getCategories().deleteItem();
	});
	$('#ctg_thumb_delete_btn').click( function() {
		this.blur();
		getCategories().deleteThumb();
	});
	
	/*
	 * #########################################################################
	 * ############################# Project Buttons ###########################
	 * #########################################################################
	 */
	
	$('#select_project').focus( function() {
		focus(getProjects());
		getProjects().change();
	});
	$('#select_project').change( function() {
		getProjects().change();
	});
	$('#btn_savePrj').click( function() {
		this.blur();
		getProjects().saveItem();
	});
	// New Project Dialog			
	$('#dialog_newPrj').dialog({
		autoOpen: false,
		width: 250,
		modal: true,
		position: [$('#btn_newPrj').offset().left-40, $('#btn_newPrj').offset().top+50],
		open: function() {
			$('#dialog_newPrj').keyup(function(e) {
			    if (e.keyCode == 13) {
			    	e.stopImmediatePropagation();
			    	e.preventDefault();
			        if (getProjects().checkAlias($('#prj_new_alias').val())) {
						$('#prj_alias').val($('#prj_new_alias').val());
						$('#prj_new_alias').val('');
						getProjects().newItem();
						$(this).dialog("close");
					}
			    	return false;
			    }
			});
		},
		buttons: {
			"Ok": function() {
				if (getProjects().checkAlias($('#prj_new_alias').val())) {
					$('#prj_alias').val($('#prj_new_alias').val());
					$('#prj_new_alias').val('');
					getProjects().newItem();
					$(this).dialog("close");
				}
			}, 
			"Cancel": function() { 
				$(this).dialog("close"); 
			} 
		}
	});
	
	$('#btn_newPrj').click( function() {
		this.blur();
		getProjects().clearFormElements(false);
		$('#dialog_newPrj').dialog('open');
	});
	$('#btn_resetPrj').click( function() {
		this.blur();
		$('#select_project').focus().change();
	});
	$('#btn_deletePrj').click( function() {
		this.blur();
		getProjects().deleteItem();
	});
	$('#prj_thumb_delete_btn').click( function() {
		this.blur();
		getProjects().deleteThumb();
	});
	$('#prj_thumb_container').click( function() {
		getProjects().showCropDialog();
	});
	
	/*
	 * #########################################################################
	 * ############################# Button Buttons ############################
	 * #########################################################################
	 */
	
	$('#select_button').focus( function() {
		focus(getButtons());
		getButtons().change();
	});
	$('#select_button').change( function() {
		getButtons().change();
	});
	$('#btn_saveBtn').click( function() {
		this.blur();
		getButtons().saveItem();
	});
	// New Button Dialog			
	$('#dialog_newBtn').dialog({
		autoOpen: false,
		width: 250,
		modal: true,
		position: [$('#btn_newBtn').offset().left-40, $('#btn_newBtn').offset().top+50],
		open: function() {
			$('#dialog_newBtn').keyup(function(e) {
			    if (e.keyCode == 13) {
			    	e.stopImmediatePropagation();
			    	e.preventDefault();
			        if (getButtons().checkAlias($('#btn_new_alias').val())) {
						$('#btn_alias').val($('#btn_new_alias').val());
						$('#btn_new_alias').val('');
						getButtons().newItem();
						$(this).dialog("close");
					}
			    	return false;
			    }
			});
		},
		buttons: {
			"Ok": function() {
				if (getButtons().checkAlias($('#btn_new_alias').val())) {
					$('#btn_alias').val($('#btn_new_alias').val());
					$('#btn_new_alias').val('');
					getButtons().newItem();
					$(this).dialog("close");
				}
			}, 
			"Cancel": function() { 
				$(this).dialog("close"); 
			} 
		}
	});
	
	$('#btn_newBtn').click( function() {
		this.blur();
		getButtons().clearFormElements(false);
		$('#dialog_newBtn').dialog('open');
	});
	$('#btn_resetBtn').click( function() {
		this.blur();
		$('#select_button').focus().change();
	});
	$('#btn_deleteBtn').click( function() {
		this.blur();
		getButtons().deleteItem();
	});
	$('#btn_thumb_delete_btn').click( function() {
		this.blur();
		getButtons().deleteThumb();
	});
	$('#btn_img_delete_btn').click( function() {
		this.blur();
		getButtons().deleteImage();
	});
	$('#btn_x').change( function() {
		getButtons().updatePreview();
	});
	$('#btn_y').change( function() {
		getButtons().updatePreview();
	});
	$('#btn_content_x').change( function() {
		getButtons().updatePreview();
	});
	$('#btn_content_y').change( function() {
		getButtons().updatePreview();
	});
	$('#btn_content_width').change( function() {
		getButtons().updatePreview();
	});
	$('#btn_content_height').change( function() {
		getButtons().updatePreview();
	});
	
	/*
	 * #########################################################################
	 * ############################# Dialogs / Utils ###########################
	 * #########################################################################
	 */
	
	// Crop Dialog			
	cropDialog = $('#dialog_crop').dialog({
		autoOpen: false,
		width: 1050,
		height: 750,
		modal: true,
		open: function(event, ui) {
			$('#dialog_crop').keyup(function(e) {
				if (e.keyCode == 13) {
					e.stopImmediatePropagation();
			    	e.preventDefault();
				    $(this).dialog("close");
					if(cropDialog.callback == 'saveThumb') {
						cropDialog.container.getInstance().saveThumb();
					} else if(cropDialog.callback == 'savePreview') {
						cropDialog.container.getInstance().savePreview();
					} else {
						
					}
					return false;
				}
			});
		},
		close: function(event, ui) {
			$('.swfupload').show();
		},
		buttons: {
			"Ok": function() {
				$(this).dialog("close");
				if(cropDialog.callback == 'saveThumb') {
					cropDialog.container.getInstance().saveThumb();
				} else if(cropDialog.callback == 'savePreview') {
					cropDialog.container.getInstance().savePreview();
				} else {
					
				}
			}, 
			"Cancel": function() {
				resetCrop();
				$(this).dialog("close");
			} 
		}
	});
	cropDialog.container = null;
	
	//TODO Replace native alert with jQuery dialog boox
	// Alert Dialog			
	/*alertDialog = $('#alertDialog').dialog({
		autoOpen: false,
		width: 300,
		height: 150,
		modal: true,
		open: function(event, ui) {
			$('#alertDialog').keyup(function(e) {
		    	e.stopImmediatePropagation();
		    	e.preventDefault();
			    $(this).dialog("close");
			    return false;
			});
		},
		close: function(event, ui) {
			$('.swfupload').show();
		},
		buttons: {
			"Ok": function(e) {
				e.stopImmediatePropagation();
		    	e.preventDefault();
			    $(this).dialog("close");
			    return false;
			} 
		}
	});*/
	
	
	/*
	 * #########################################################################
	 * ########################### Keyboard controls ###########################
	 * #########################################################################
	 */
	
	$('.yform').keyup(function(e){
		if(e.keyCode == 13) {
			current_container.saveItem();
		}
	});

	
};


